﻿//using Microsoft.Extensions.Hosting;
//using Microsoft.Extensions.Logging;
//using Microsoft.Extensions.Options;
//using System;
//using System.Threading;
//using System.Threading.Tasks;

//namespace Xms.Abp;

//public class WindowsDesktopLifetime : IHostLifetime, IDisposable
//{
//    protected IServiceProvider ServiceProvider { get; }
//    protected Application Application { get; private set; }

//    private IHostApplicationLifetime ApplicationLifetime { get; }

//    private IHostEnvironment Environment { get; }

//    private ILogger Logger { get; }

//    private readonly HostOptions _hostOptions;

//    private readonly WindowsDesktopLifetimeOptions _desktopOptions;

//    private readonly TaskCompletionSource<object> _delayStart = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);

//    private readonly ManualResetEventSlim _delayStop = new ManualResetEventSlim();

//    public WindowsDesktopLifetime(
//        IHostEnvironment environment,
//        IHostApplicationLifetime applicationLifetime,
//        ILoggerFactory loggerFactory,
//        IOptions<HostOptions> optionsAccessor,
//        IOptions<WindowsDesktopLifetimeOptions> desktopOptionsAccesser,
//        IServiceProvider serviceProvider)
//    {
//        if (environment == null)
//        {
//            throw new ArgumentNullException(nameof(environment));
//        }
//        Environment = environment;
//        if (applicationLifetime == null)
//        {
//            throw new ArgumentNullException(nameof(applicationLifetime));
//        }
//        ApplicationLifetime = applicationLifetime;
//        Logger = loggerFactory.CreateLogger("Microsoft.Hosting.Lifetime");
//        if (optionsAccessor == null)
//        {
//            throw new ArgumentNullException(nameof(optionsAccessor));
//        }
//        if (desktopOptionsAccesser == null)
//        {
//            throw new ArgumentNullException(nameof(desktopOptionsAccesser));
//        }
//        _hostOptions = optionsAccessor.Value;
//        _desktopOptions = desktopOptionsAccesser.Value;
//        ServiceProvider = serviceProvider;
//    }

//    public async Task StopAsync(CancellationToken cancellationToken)
//    {
//        ApplicationLifetime.StopApplication();
//        _delayStop.Wait(_hostOptions.ShutdownTimeout);
//        await Task.CompletedTask;
//    }

//    public async Task WaitForStartAsync(CancellationToken cancellationToken)
//    {
//        cancellationToken.Register(() =>
//        {
//            _delayStart.TrySetCanceled();
//        });
//        ApplicationLifetime.ApplicationStarted.Register(delegate ()
//        {
//            Logger.LogInformation("Application started. Hosting environment: {envName}; Content root path: {contentRoot}", new object[]
//            {
//                    Environment.EnvironmentName,
//                    Environment.ContentRootPath
//            });
//        });
//        ApplicationLifetime.ApplicationStopping.Register(delegate ()
//        {
//            Logger.LogInformation("Application is shutting down...", Array.Empty<object>());
//        });
//        ApplicationLifetime.ApplicationStopped.Register(delegate ()
//        {
//            _delayStop.Set();
//        });

//        var STAThread = new Thread(p =>
//        {
//            var cancellationToken = (CancellationToken)p;
//            OnStartup(cancellationToken);
//        });
//        STAThread.SetApartmentState(ApartmentState.STA);
//        STAThread.Start(cancellationToken);
//        STAThread.Join();
//        await _delayStart.Task;
//    }

//    protected void OnStartup(CancellationToken cancellationToken)
//    {
//        try
//        {
//            Application = ServiceProvider.GetService(_desktopOptions.ApplicationType) as Application;
//            cancellationToken.Register(() =>
//            {
//                Application.Shutdown();
//            });
//            Application.Startup += (o, e) =>
//            {
//                if (Application.GetType() == typeof(Application))
//                {
//                    Application.MainWindow = ServiceProvider.GetService(_desktopOptions.MainWindowType) as Window;
//                    Application.MainWindow.Show();
//                }
//                Application.Exit += (o, e) =>
//                {
//                    _delayStart.SetCanceled();
//                        //StopAsync(cancellationToken).Wait();
//                    };
//            };
//            Application.Run();
//            _delayStart.TrySetException(new InvalidOperationException("Stopped without starting"));
//        }
//        catch (Exception ex)
//        {
//            _delayStart.TrySetException(ex);
//        }
//    }

//    public void Dispose()
//    {
//        this._delayStop.Set();
//    }
//}
